package com.msmall.community.keyword.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.Constants;
import com.msmall.community.keyword.dao.KeywordDao;
import com.msmall.community.keyword.model.Keyword;
import com.msmall.community.keyword.service.KeywordManager;
import com.msmall.community.keyword.util.KeywordUtil;

public class KeywordManagerImpl extends BaseManagerImpl<Keyword, Long> implements KeywordManager{
	
	private static final Log logger = LogFactory.getLog(KeywordManagerImpl.class);
	
	private KeywordDao keywordDao;
	
	public void setKeywordDao(KeywordDao keywordDao) {
		this.keywordDao = keywordDao;
	}
	
	/**
	 * 后台管理员管理推荐，包括审核，显示位置
	 * @param commend
	 * @param userid
	 */
	public void addKeyword(File image,String filename,Keyword keyword, Long userid, String uat){
		try{
			if(image != null){
				String[] pathinfo = KeywordUtil.saveImage(image, filename,uat);
				keyword.setImageName(pathinfo[1]);
				keyword.setImagePath(pathinfo[0]);
			}
			keywordDao.save(keyword);
		}catch(Exception e){
			logger.error(e);
		}
	}
	
	/**
	 * 后台管理用户删除一个关键字
	 */
	public void removeKeyword(Long keywordid, Long userid){
		keywordDao.remove(Keyword.class, keywordid);
	}
	/**
	 * 后台管理用户删除一个关键字
	 */
	public void removeKeywords(String keywordids, Long userid){
		String[] ids = keywordids.split(",");
		for(int i=0;i<ids.length;i++){
			if(!StringUtils.isEmpty(ids[i])){
				removeKeyword(Long.parseLong(ids[i]), userid);
			}
		}
	}
	
	/**
	 * 载入关键字到缓存
	 */
	public void refresh(){
		List<Keyword> keywords = keywordDao.getAll(Keyword.class);
		Map<Short, List<Keyword>> maps = new HashMap<Short, List<Keyword>>();
		List<Keyword> list;
		for(Keyword kd : keywords){
			list = maps.get(kd.getModule());
			if(list == null){
				list = new ArrayList<Keyword>();
				maps.put(kd.getModule(), list);
			}
			list.add(kd);
		}
		CacheFactory.getInstance().getCache(Constants.CACHE_NAME_COMMON).put(Constants.CACHE_KEY_KEYWORD, maps);
	}
}
